let currentNavStr = sessionStorage.getItem("currentNav");
let currentNav = currentNavStr && currentNavStr != "undefined" ? JSON.parse(currentNavStr) : "";

let currentTabStr = sessionStorage.getItem("currentTab");
let currentTab = currentTabStr ? JSON.parse(currentTabStr) : "";

let tabsStr = sessionStorage.getItem("tabs");
let tabs = tabsStr ? JSON.parse(tabsStr) : [];

let state = {
  tabs,
  currentNav,
  currentTab
};

let mutations = {
  // 设置当前用户的项目列表
  setTabs(state, data) {
    state.tabs = data;
    sessionStorage.setItem("tabs", JSON.stringify(data));
  },
  setCurrentNav(state, data) {
    state.currentNav = data;
    sessionStorage.setItem("currentNav", JSON.stringify(data));
  },
  setCurrentTab(state, data) {
    state.currentTab = data;
    this.commit("setCurrentNav", data.menuType);
    sessionStorage.setItem("currentTab", JSON.stringify(data));
    if (!data) return;

    let index = state.tabs.findIndex(tab => tab.id === data.id);
    let tabs = JSON.parse(JSON.stringify(state.tabs));
    if (~index) {
      tabs[index] = { ...data };
    } else {
      tabs.push(data);
    }
    this.commit("setTabs", tabs);
  },
  deleteTab(state, id) {
    let index = state.tabs.findIndex(tab => tab.id === id);
    if (~index) {
      let tabs = JSON.parse(JSON.stringify(state.tabs));
      tabs.splice(index, 1);
      this.commit("setTabs", tabs);
      if (id === state.currentTab.id && state.tabs.length > 0) {
        currentTab = state.tabs[state.tabs.length - 1];
        this.commit("setCurrentTab", currentTab);
      }
      if (state.tabs.length === 0) {
        this.commit("setCurrentTab", "");
      }
    }
  },
  updataTabContent(state, tab) {
    state.currentTab.content = tab.content;
  }
};

export default {
  state,
  mutations
};
